import api, { type KunlunModelsAdminLoginRequest } from "@/api";
import { useAuthStore } from "@/store";
import type { Claims } from "@/types";
import {
	Button,
	Card,
	ConfigProvider,
	Form,
	Input,
} from "@arco-design/web-react";
import { IconLock, IconUser } from "@arco-design/web-react/icon";

import { useMutation } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import { type CSSProperties, memo } from "react";

type LoginSearch = {
	returnUrl?: string;
};

const LoginTitle = memo(() => (
	<h1 style={{ color: "white", fontSize: 24 }}>昆仑健康运营平台</h1>
));

export const Route = createFileRoute("/login")({
	validateSearch: (search: Record<string, unknown>): LoginSearch => {
		return { returnUrl: (search?.returnUrl as string) || "" };
	},
	component: function Login() {
		const { login } = useAuthStore();
		const { returnUrl } = Route.useSearch();

		const loginMutation = useMutation({
			mutationFn: api.adminUserLoginCreate,
		});

		const handleSubmit = async (values: KunlunModelsAdminLoginRequest) => {
			const res = await loginMutation.mutateAsync(values);
			login(res as Claims);
			if (returnUrl) {
				location.href = returnUrl;
			} else {
				location.href = "/";
			}
		};

		const formItemStyle: CSSProperties = {
			justifyContent: "center",
		};

		return (
			<ConfigProvider size="small">
				<div className="flex w-full h-dvh justify-center items-center bg-[#f2f3f5]">
					<Card
						title={<LoginTitle />}
						className="w-[446px] h-[308px] shadow-[#ccc] text-center flex flex-col"
						headerStyle={{
							backgroundColor: "rgb(var(--primary-6))",
							height: 88,
						}}
						bodyStyle={{
							flex: 1,
							display: "flex",
							alignItems: "center",
						}}
					>
						<Form onSubmit={handleSubmit}>
							<Form.Item<KunlunModelsAdminLoginRequest>
								field={"account"}
								rules={[
									{ required: true, message: "请输入手机号码" },
									{ match: /\d{11}/, message: "请输入有效的手机号码" },
								]}
								style={formItemStyle}
							>
								<Input prefix={<IconUser />} placeholder="请输入手机号码" />
							</Form.Item>
							<Form.Item<KunlunModelsAdminLoginRequest>
								field={"password"}
								rules={[{ required: true, message: "请输入密码" }]}
								style={formItemStyle}
							>
								<Input.Password
									prefix={<IconLock />}
									placeholder="请输入密码"
								/>
							</Form.Item>
							<Form.Item style={formItemStyle}>
								<Button
									type="primary"
									htmlType="submit"
									long
									loading={loginMutation.isPending}
								>
									登录
								</Button>
							</Form.Item>
						</Form>
					</Card>
				</div>
			</ConfigProvider>
		);
	},
});
